package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.ForumDao;
import com.example.simpleforum.model.Forum;
import com.example.simpleforum.model.User;
import com.example.simpleforum.model.User.Role;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 板块列表Servlet（仅主管理员可用）
 */
public class ForumListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        // 检查用户是否为主管理员
        if (user.getRole() != Role.main_admin) {
            // 用户不是主管理员，无权访问板块管理页面
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            return;
        }
        
        // 获取所有板块
        ForumDao forumDao = new ForumDao();
        List<Forum> forums = forumDao.findAll();
        
        // 设置属性并转发到JSP页面
        request.setAttribute("forums", forums);
        request.getRequestDispatcher("/forumList.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // POST请求也执行相同操作
        doGet(request, response);
    }
}